package org.dingfugui.triple.protocol.binary.aio;

import org.dingfugui.triple.connection.Connection;
import org.dingfugui.triple.link.Link;
import org.dingfugui.triple.protocol.Translator;
import org.dingfugui.triple.rpc.RequestMessage;
import org.dingfugui.triple.rpc.ResponseMessage;

/**
 * Created by fugui.ding on 2015/6/10.
 */
public class AioRequestHandler {

    Link link;
    Translator messageHandler;

    public AioRequestHandler(Link link, Translator messageHandler) {
        this.link = link;
        this.messageHandler = messageHandler;
    }

    public ResponseMessage handle(RequestMessage request) {

        Connection con = null;
        try {
            con = link.getConnection();

            byte[] requestMessage = messageHandler.encodeRequest(request);
            con.write(requestMessage);
            byte[] responseMessage = con.read();

            ResponseMessage response = messageHandler.decodeResponse(responseMessage);

            return response;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            link.destory(con);
        }
    }
}
